package org.spring.test;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;

public class LoginErrorPhaseListener implements PhaseListener {
	private static final long serialVersionUID = -1216620620302322995L;

	@Override
	public void beforePhase(final PhaseEvent arg0) {
		FacesContext context = FacesContext.getCurrentInstance();
		Exception e = (Exception) context.getExternalContext().getSessionMap().get(WebAttributes.AUTHENTICATION_EXCEPTION);

		if (e instanceof BadCredentialsException) {
			context.getExternalContext().getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
			System.out.println("Username or password not valid.");
			FacesMessage message = new FacesMessage("Usuario o password incorrectos.");
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			context.addMessage("", message);
			return;
		}
		if (e instanceof SessionAuthenticationException) {
			context.getExternalContext().getSessionMap().put(WebAttributes.AUTHENTICATION_EXCEPTION, null);
			System.out.println("Max Session.");
			FacesMessage message = new FacesMessage("Se exedio el numero de conexiones por usuarios.");
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			context.addMessage("", message);
			return;
		}

	//	context.getExternalContext().getSessionMap().put("user", "Hola Mundo!!!!");

	}

	@Override
	public void afterPhase(final PhaseEvent arg0) {
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RENDER_RESPONSE;
	}

}